<template>
    <div class="dictionary-page">
        <el-container>
            <el-header height="auto">
                <el-card shadow="never">
                    <el-form :inline="true" :model="searchForm" label-width="auto" class="filter-form">
                        <el-form-item label="字典编号">
                            <el-input v-model="searchForm.dictionaryCode" clearable placeholder="字典编号"
                                style="width: 200px" />
                        </el-form-item>
                        <el-form-item label="字典名称">
                            <el-input v-model="searchForm.dictionaryName" clearable placeholder="字典名称"
                                style="width: 200px" />
                        </el-form-item>
                        <el-form-item>
                            <el-space>
                                <el-button type="primary" @click="handleQuery">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                    查询
                                </el-button>
                                <el-button @click="handleReset">
                                    <el-icon>
                                        <Refresh />
                                    </el-icon>
                                    重置
                                </el-button>
                            </el-space>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-header>

            <el-main>
                <el-card shadow="never">
                    <div class="toolbar">
                        <el-space wrap>
                            <el-button type="primary" size="small" @click="handleCreate">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                新增
                            </el-button>
                            <el-button type="danger" size="small" @click="handleBatchDelete"
                                :disabled="!multipleSelection.length">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                                删除
                            </el-button>
                            <el-button size="small" @click="handleRefresh">
                                <el-icon>
                                    <Refresh />
                                </el-icon>
                                刷新
                            </el-button>
                            <el-button type="success" size="small" @click="handleImport">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                导入
                            </el-button>
                            <el-button size="small" @click="handleExport">
                                <el-icon>
                                    <Download />
                                </el-icon>
                                导出
                            </el-button>
                        </el-space>
                    </div>

                    <el-table ref="multipleTableRef" v-loading="loading" :data="tableData" border style="width: 100%"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" />
                        <el-table-column type="index" label="#" width="60" />
                        <el-table-column prop="dictionaryCode" label="字典编号" min-width="180" />
                        <el-table-column prop="dictionaryName" label="字典名称" min-width="150" />
                        <el-table-column prop="dictionaryDesc" label="描述" min-width="200">
                            <template #default="{ row }">
                                {{ row.dictionaryDesc || '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="280">
                            <template #default="{ row }">
                                <el-button link type="primary" size="small" @click="handleEdit(row)">
                                    编辑
                                </el-button>
                                <el-button link type="success" size="small" @click="handleConfig(row)">
                                    字典配置
                                </el-button>
                                <el-button link type="danger" size="small" @click="handleDelete(row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <el-card shadow="never" class="pagination-card">
                    <div class="pagination-bar">
                        <div class="pagination-info">
                            共{{ page.listCount }}条， 每页{{ page.pagesize }}条， 当前第{{ page.pageindex }}/{{ page.pageCount
                            }}页
                        </div>
                        <div class="pagination-controls">
                            <el-button class="pagination-btn" link type="primary" size="small"
                                @click="page.pageindex = 1">
                                首页
                            </el-button>
                            <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
                                :page-sizes="[10, 20, 50, 100]" :total="page.listCount" prev-text="上一页" next-text="下一页"
                                :background="true" layout="prev, pager, next" />
                            <el-button class="pagination-btn" link type="primary" size="small"
                                @click="page.pageindex = page.pageCount || 1">
                                尾页
                            </el-button>
                            <span class="pagination-jump">
                                前往
                                <el-input-number v-model="page.pageindex" :min="1" :max="page.pageCount || 1"
                                    size="small" controls-position="right" style="width: 90px" />
                                页
                            </span>
                        </div>
                    </div>
                </el-card>
            </el-main>
        </el-container>

        <!-- 新增/编辑字典弹框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑字典' : '新增字典'" width="600px" @close="handleDialogClose">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="字典编号" prop="dictionaryCode">
                    <el-input v-model="form.dictionaryCode" placeholder="自动获取系统编号" readonly class="form-input">
                        <template #append>
                            <el-button @click="generateDictionaryCode" :loading="generatingCode">自动生成</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="字典名称" prop="dictionaryName">
                    <el-input v-model="form.dictionaryName" placeholder="请输入字典名称" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSave" :loading="saving">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 字典配置弹框 -->
        <el-dialog v-model="configDialogVisible" :title="`字典配置 - ${currentConfigDictionaryName}`" width="1200px"
            @close="handleConfigDialogClose">
            <div class="config-toolbar">
                <el-button type="primary" size="small" @click="handleConfigAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新增
                </el-button>
                <el-button type="danger" size="small" @click="handleConfigBatchDelete"
                    :disabled="!configMultipleSelection.length">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    删除
                </el-button>
                <el-button size="small" @click="fetchConfigData">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </div>

            <el-table ref="configTableRef" v-loading="configLoading" :data="configTableData" border style="width: 100%"
                @selection-change="handleConfigSelectionChange">
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" label="#" width="60" />
                <el-table-column prop="dictionaryCode" label="字典编号" min-width="180" />
                <el-table-column prop="dictionaryName" label="字典名称" min-width="150" />
                <el-table-column label="所属字典" min-width="150">
                    <template #default>
                        {{ currentConfigDictionaryName }}
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="200">
                    <template #default="{ row }">
                        {{ row.description || '无' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="200">
                    <template #default="{ row }">
                        <el-button link type="primary" size="small" @click="handleConfigEdit(row)">
                            编辑
                        </el-button>
                        <el-button link type="danger" size="small" @click="handleConfigDelete(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <div style="padding: 20px; text-align: center; color: #909399;">
                        暂无子集数据，请点击"新增"添加
                    </div>
                </template>
            </el-table>

            <div class="config-pagination" v-if="configPage.listCount > 0">
                <div class="pagination-info">
                    共{{ configPage.listCount }}条， 每页{{ configPage.pagesize }}条， 当前第{{ configPage.pageindex }}/{{
                    configPage.pageCount }}页
                </div>
                <div class="pagination-controls">
                    <el-button class="pagination-btn" link type="primary" size="small"
                        @click="configPage.pageindex = 1">
                        首页
                    </el-button>
                    <el-pagination v-model:current-page="configPage.pageindex" v-model:page-size="configPage.pagesize"
                        :page-sizes="[10, 20, 50, 100]" :total="configPage.listCount" prev-text="上一页" next-text="下一页"
                        :background="true" layout="prev, pager, next" />
                    <el-button class="pagination-btn" link type="primary" size="small"
                        @click="configPage.pageindex = configPage.pageCount || 1">
                        尾页
                    </el-button>
                    <span class="pagination-jump">
                        前往
                        <el-input-number v-model="configPage.pageindex" :min="1" :max="configPage.pageCount || 1"
                            size="small" controls-position="right" style="width: 90px" />
                        页
                    </span>
                </div>
            </div>

            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="configDialogVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 新增/编辑字典配置弹框 -->
        <el-dialog v-model="configFormDialogVisible" :title="configFormIsEdit ? '编辑字典配置' : '新增字典配置'" width="600px"
            @close="handleConfigFormDialogClose">
            <el-form ref="configFormRef" :model="configForm" :rules="configFormRules" label-width="100px">
                <el-form-item label="字典编号" prop="dictionaryCode">
                    <el-input v-model="configForm.dictionaryCode" placeholder="自动获取系统编号" readonly class="form-input">
                        <template #append>
                            <el-button @click="generateConfigDictionaryCode"
                                :loading="generatingConfigCode">自动生成</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="字典名称" prop="dictionaryName">
                    <el-input v-model="configForm.dictionaryName" placeholder="请输入字典名称" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="configForm.dictionaryDesc" type="textarea" :rows="4" placeholder="请输入描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="configFormDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfigFormSave" :loading="configFormSaving">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Delete, Upload, Download } from '@element-plus/icons-vue'
import router from '@/router'
import myaxios from '@/http/MyAxios'
import moment from 'moment'

interface DictionaryConfigItem {
    dictionaryId: number
    dictionaryCode: string
    dictionaryName: string
    description?: string
    parentId?: number | null
}

interface DictionaryItem {
    dictionaryId: number
    dictionaryCode: string
    dictionaryName: string
    description?: string
    parentId?: number | null
    parentName?: string
    displayName?: string
}

const loading = ref(false)
const tableData = ref<DictionaryItem[]>([])
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<DictionaryItem[]>([])

const searchForm = reactive({
    dictionaryCode: '',
    dictionaryName: '',
})

const page = reactive({
    pageindex: 1,
    pagesize: 10,
    listCount: 0,
    pageCount: 0,
})

// 弹框相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const saving = ref(false)
const isEdit = ref(false)
const generatingCode = ref(false)
const form = reactive({
    dictionaryId: '',
    dictionaryCode: '',
    dictionaryName: '',
    description: '',
})

const rules: FormRules = {
    dictionaryName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
}

// 字典配置弹框相关
const configDialogVisible = ref(false)
const configTableRef = ref<TableInstance>()
const configLoading = ref(false)
const configTableData = ref<DictionaryConfigItem[]>([])
const configMultipleSelection = ref<DictionaryConfigItem[]>([])
const currentConfigDictionaryId = ref<string | number>('')
const currentConfigDictionaryName = ref('')

const configPage = reactive({
    pageindex: 1,
    pagesize: 10,
    listCount: 0,
    pageCount: 0,
})

// 字典配置表单弹框相关
const configFormDialogVisible = ref(false)
const configFormRef = ref<FormInstance>()
const configFormSaving = ref(false)
const configFormIsEdit = ref(false)
const generatingConfigCode = ref(false)
const configForm = reactive({
    dictionaryId: '',
    dictionaryCode: '',
    dictionaryName: '',
    dictionaryDesc: '',
    parentId: '',
})

const configFormRules: FormRules = {
    dictionaryName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
}

// 获取字典列表
const fetchData = async () => {
    loading.value = true
    try {
        const params: any = {
            Pageindex: page.pageindex,
            PageSize: page.pagesize,
        }
        if (searchForm.dictionaryCode) {
            params.DictionaryCode = searchForm.dictionaryCode
        }
        if (searchForm.dictionaryName) {
            params.DictionaryName = searchForm.dictionaryName
        }

        const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
        const result = res.data || {}
        if (result.code === 200) {
            const allData = result.data?.data || []
            // 只显示父级字典，过滤掉子级（有parentId且不为0或null的）
            tableData.value = allData.filter((item: DictionaryItem) => {
                return !item.parentId || item.parentId === 0 || item.parentId === null
            })
            page.listCount = tableData.value.length
            page.pageCount = Math.ceil(page.listCount / page.pagesize) || 1
        } else {
            ElMessage.error(result.message || '获取字典列表失败')
        }
    } catch (error) {
        console.error('获取字典列表失败:', error)
        ElMessage.error('获取字典列表失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 查询
const handleQuery = () => {
    page.pageindex = 1
    fetchData()
}

// 重置
const handleReset = () => {
    searchForm.dictionaryCode = ''
    searchForm.dictionaryName = ''
    page.pageindex = 1
    fetchData()
}

// 刷新
const handleRefresh = () => {
    fetchData()
}

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
    const now = new Date()
    const segments = (rule?.timeRule || '')
        .split(',')
        .map((s: string) => s.trim().toUpperCase())
        .filter(Boolean)
        .sort((a: string, b: string) => {
            const indexA = TIME_SEGMENT_ORDER.indexOf(a)
            const indexB = TIME_SEGMENT_ORDER.indexOf(b)
            if (indexA === -1 && indexB === -1) return 0
            if (indexA === -1) return 1
            if (indexB === -1) return -1
            return indexA - indexB
        })

    const datePart = segments
        .map((seg: string) => {
            switch (seg) {
                case 'YYYY':
                    return String(now.getFullYear())
                case 'YY':
                    return String(now.getFullYear()).slice(-2)
                case 'MM':
                    return pad(now.getMonth() + 1)
                case 'DD':
                    return pad(now.getDate())
                case 'HH':
                    return pad(now.getHours())
                case 'MI':
                    return pad(now.getMinutes())
                case 'SS':
                    return pad(now.getSeconds())
                default:
                    return ''
            }
        })
        .join('')
    const seq = '1'.padStart(rule?.serialLength || 3, '0')
    return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestDictionaryCode = async (targetCode: string, targetName: string) => {
    try {
        const res = await myaxios.get('/api/Number/GenerateNumber', {
            params: { targetCode, targetName }
        })
        if (res?.data?.code === 200 && res?.data?.data) {
            return String(res.data.data)
        }
        throw new Error(res?.data?.message || '生成编号失败')
    } catch (err) {
        console.warn('[dictionary] GenerateNumber 接口不可用，尝试规则生成', err)
        const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
            params: { targetCode, targetName }
        })
        const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
        if (list.length > 0) {
            return buildCodeFromRule(list[0])
        }
        throw new Error('未找到对应的编号规则，请先在编号规则中配置')
    }
}

const generateDictionaryCode = async () => {
    generatingCode.value = true
    try {
        const code = await requestDictionaryCode('Dictionary', '字典')
        form.dictionaryCode = code
        ElMessage.success('编号生成成功')
    } catch (err: any) {
        ElMessage.error(err?.message || '生成编号失败')
    } finally {
        generatingCode.value = false
    }
}

// 新增
const handleCreate = () => {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: DictionaryItem) => {
    isEdit.value = true
    resetForm()
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryDetail', {
            params: { dictionaryId: row.dictionaryId },
        })
        const result = res.data || {}
        if (result.code === 200) {
            const detailData = result.data || {}
            form.dictionaryId = detailData.dictionaryId || ''
            form.dictionaryCode = detailData.dictionaryCode || ''
            form.dictionaryName = detailData.dictionaryName || ''
            form.description = detailData.dictionaryDesc || detailData.description || ''
            dialogVisible.value = true
        } else {
            ElMessage.error(result.message || '获取字典详情失败')
        }
    } catch (error) {
        console.error('获取字典详情失败:', error)
        ElMessage.error('获取字典详情失败，请稍后重试')
    }
}

// 重置表单
const resetForm = () => {
    form.dictionaryId = ''
    form.dictionaryCode = ''
    form.dictionaryName = ''
    form.description = ''
    formRef.value?.resetFields()
}

// 关闭弹框
const handleDialogClose = () => {
    resetForm()
}

// 保存
const handleSave = async () => {
    if (!formRef.value) return

    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) return

    if (!isEdit.value && !form.dictionaryCode) {
        await generateDictionaryCode()
        if (!form.dictionaryCode) return
    }

    saving.value = true
    try {
        const url = isEdit.value
            ? '/api/Dictionary/UpdateDictionary'
            : '/api/Dictionary/CreateDictionary'
        const payload: any = {
            ...form,
            dictionaryDesc: form.description,
        }
        // 更新操作使用PUT方法，新增操作使用POST方法
        const res = isEdit.value
            ? await myaxios.put(url, payload)
            : await myaxios.post(url, payload)
        const result = res.data || {}
        if (result.code === 200) {
            ElMessage.success(result.message || '保存成功')
            dialogVisible.value = false
            fetchData()
        } else {
            ElMessage.error(result.message || '保存失败')
        }
    } catch (error) {
        console.error('保存字典失败:', error)
        ElMessage.error('保存失败，请稍后重试')
    } finally {
        saving.value = false
    }
}

// 字典配置
const handleConfig = (row: DictionaryItem) => {
    currentConfigDictionaryId.value = row.dictionaryId
    currentConfigDictionaryName.value = row.dictionaryName
    configPage.pageindex = 1
    configDialogVisible.value = true
    fetchConfigData()
}

// 获取字典配置列表（子级字典）
const fetchConfigData = async () => {
    if (!currentConfigDictionaryId.value) {
        ElMessage.warning('缺少字典ID参数')
        return
    }

    configLoading.value = true
    try {
        // GetDictionaryChildren 接口会根据ParentId参数自动过滤子级数据
        const params: any = {
            Pageindex: configPage.pageindex,
            PageSize: configPage.pagesize,
            ParentId: currentConfigDictionaryId.value,
        }

        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', { params })
        const result = res.data || {}
        if (result.code === 200) {
            const rawData = result.data?.data || []
            // 后端返回的字段名与前端期望的字段名不一致，需要进行映射
            // 后端：dictionaryParentId, dictionaryDesc
            // 前端：parentId, description
            const mappedData: DictionaryConfigItem[] = rawData.map((item: any) => ({
                dictionaryId: item.dictionaryId,
                dictionaryCode: item.dictionaryCode,
                dictionaryName: item.dictionaryName,
                description: item.dictionaryDesc || item.description || '',
                parentId: item.dictionaryParentId || item.parentId || null,
            }))

            configTableData.value = mappedData
            // 使用后端返回的分页信息
            configPage.listCount = result.data?.listCount || mappedData.length
            configPage.pageCount = result.data?.pageCount || Math.ceil(configPage.listCount / configPage.pagesize) || 1
        } else {
            ElMessage.error(result.message || '获取字典配置失败')
        }
    } catch (error) {
        console.error('获取字典配置失败:', error)
        ElMessage.error('获取字典配置失败，请稍后重试')
    } finally {
        configLoading.value = false
    }
}

// 关闭字典配置弹框
const handleConfigDialogClose = () => {
    configTableData.value = []
    configMultipleSelection.value = []
    currentConfigDictionaryId.value = ''
    currentConfigDictionaryName.value = ''
}

// 字典配置选择变化
const handleConfigSelectionChange = (val: DictionaryConfigItem[]) => {
    configMultipleSelection.value = val
}

// 生成字典配置编号
const generateConfigDictionaryCode = async () => {
    generatingConfigCode.value = true
    try {
        const code = await requestDictionaryCode('Dictionary', '字典配置')
        configForm.dictionaryCode = code
        ElMessage.success('编号生成成功')
    } catch (err: any) {
        ElMessage.error(err?.message || '生成编号失败')
    } finally {
        generatingConfigCode.value = false
    }
}

// 新增字典配置
const handleConfigAdd = async () => {
    if (!currentConfigDictionaryId.value) {
        ElMessage.warning('缺少父级字典ID')
        return
    }
    configFormIsEdit.value = false
    resetConfigForm()
    // 设置父级ID为当前字典配置弹框中打开的父级字典的主键
    configForm.parentId = String(currentConfigDictionaryId.value)
    // 不自动生成编号，让用户点击按钮生成
    configForm.dictionaryCode = ''
    configFormDialogVisible.value = true
}

// 编辑字典配置
const handleConfigEdit = async (row: DictionaryConfigItem) => {
    configFormIsEdit.value = true
    resetConfigForm()
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryDetail', {
            params: { dictionaryId: row.dictionaryId },
        })
        const result = res.data || {}
        if (result.code === 200) {
            const detailData = result.data || {}
            // 映射后端字段到前端字段
            configForm.dictionaryId = detailData.dictionaryId || ''
            configForm.dictionaryCode = detailData.dictionaryCode || ''
            configForm.dictionaryName = detailData.dictionaryName || ''
            configForm.dictionaryDesc = detailData.dictionaryDesc || detailData.dictionaryDesc || ''
            configForm.parentId = detailData.dictionaryParentId || detailData.parentId || ''
            configFormDialogVisible.value = true
        } else {
            ElMessage.error(result.message || '获取字典详情失败')
        }
    } catch (error) {
        console.error('获取字典详情失败:', error)
        ElMessage.error('获取字典详情失败，请稍后重试')
    }
}

// 重置字典配置表单
const resetConfigForm = () => {
    configForm.dictionaryId = ''
    configForm.dictionaryCode = ''
    configForm.dictionaryName = ''
    configForm.dictionaryDesc = ''
    configForm.parentId = ''
    configFormRef.value?.resetFields()
}

// 关闭字典配置表单弹框
const handleConfigFormDialogClose = () => {
    resetConfigForm()
}

// 保存字典配置
const handleConfigFormSave = async () => {
    if (!configFormRef.value) return

    const valid = await configFormRef.value.validate().catch(() => false)
    if (!valid) return

    if (!currentConfigDictionaryId.value) {
        ElMessage.error('缺少父级字典ID')
        return
    }

    // 如果是新增且编号为空，自动生成编号
    if (!configFormIsEdit.value && !configForm.dictionaryCode) {
        await generateConfigDictionaryCode()
        if (!configForm.dictionaryCode) {
            ElMessage.warning('请先生成字典编号')
            return
        }
    }

    configFormSaving.value = true
    try {
        const url = configFormIsEdit.value
            ? '/api/Dictionary/UpdateDictionary'
            : '/api/Dictionary/CreateDictionary'

        // 确保父级ID始终使用当前字典配置弹框中打开的父级字典的主键
        // 后端可能期望 dictionaryParentId 字段，但也兼容 parentId
        const payload: any = {
            ...configForm,
            parentId: currentConfigDictionaryId.value,
            dictionaryParentId: currentConfigDictionaryId.value, // 同时传递后端期望的字段名
            dictionaryDesc: configForm.dictionaryDesc, // 映射description到dictionaryDesc
        }

        // 如果是新增，确保parentId被设置
        if (!configFormIsEdit.value) {
            payload.parentId = currentConfigDictionaryId.value
            payload.dictionaryParentId = currentConfigDictionaryId.value
        }

        // 更新操作使用PUT方法，新增操作使用POST方法
        const res = configFormIsEdit.value
            ? await myaxios.put(url, payload)
            : await myaxios.post(url, payload)
        const result = res.data || {}
        if (result.code === 200) {
            ElMessage.success(result.message || '保存成功')
            configFormDialogVisible.value = false
            fetchConfigData()
        } else {
            ElMessage.error(result.message || '保存失败')
        }
    } catch (error) {
        console.error('保存字典配置失败:', error)
        ElMessage.error('保存失败，请稍后重试')
    } finally {
        configFormSaving.value = false
    }
}

// 删除字典配置
const handleConfigDelete = (row: DictionaryConfigItem) => {
    ElMessageBox.confirm('确认删除该字典配置吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const res = await myaxios.delete('/api/Dictionary/DeleteDictionary', {
                    params: { dictionaryId: row.dictionaryId },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '删除成功')
                    // 删除后清空选中状态
                    configMultipleSelection.value = []
                    // 检查删除后当前页是否还有数据
                    const currentPageDataCount = configTableData.value.length
                    // 如果当前页只剩一条数据（刚删除的），且不是第一页，则跳转到上一页
                    if (currentPageDataCount === 1 && configPage.pageindex > 1) {
                        configPage.pageindex = configPage.pageindex - 1
                    }
                    // 刷新数据
                    fetchConfigData()
                } else {
                    ElMessage.error(result.message || '删除失败')
                }
            } catch (error) {
                console.error('删除字典配置失败:', error)
                ElMessage.error('删除失败，请稍后重试')
            }
        })
        .catch(() => { })
}

// 批量删除字典配置
const handleConfigBatchDelete = () => {
    if (!configMultipleSelection.value.length) {
        ElMessage.warning('请选择需要删除的字典配置')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${configMultipleSelection.value.length}条字典配置吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const ids = configMultipleSelection.value.map((item) => item.dictionaryId).join(',')
                const deleteCount = configMultipleSelection.value.length
                const res = await myaxios.delete('/api/Dictionary/BatchDeleteDictionary', {
                    params: { dictionaryIds: ids },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '批量删除成功')
                    // 删除后清空选中状态
                    configMultipleSelection.value = []
                    // 检查删除后当前页是否还有数据
                    const currentPageDataCount = configTableData.value.length
                    // 如果删除的数量等于当前页的数据量，且不是第一页，则跳转到上一页
                    if (deleteCount >= currentPageDataCount && configPage.pageindex > 1) {
                        configPage.pageindex = configPage.pageindex - 1
                    }
                    // 刷新数据
                    fetchConfigData()
                } else {
                    ElMessage.error(result.message || '批量删除失败')
                }
            } catch (error) {
                console.error('批量删除字典配置失败:', error)
                ElMessage.error('批量删除失败，请稍后重试')
            }
        })
        .catch(() => { })
}

// 监听字典配置分页变化
watch(
    () => [configPage.pageindex, configPage.pagesize],
    () => {
        if (configDialogVisible.value) {
            fetchConfigData()
        }
    },
)

// 删除单个
const handleDelete = (row: DictionaryItem) => {
    ElMessageBox.confirm('确认删除该字典吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const res = await myaxios.delete('/api/Dictionary/DeleteDictionary', {
                    params: { dictionaryId: row.dictionaryId },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '删除成功')
                    fetchData()
                } else {
                    ElMessage.error(result.message || '删除失败')
                }
            } catch (error) {
                console.error('删除字典失败:', error)
                ElMessage.error('删除失败，请稍后重试')
            }
        })
        .catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (!multipleSelection.value.length) {
        ElMessage.warning('请选择需要删除的字典')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${multipleSelection.value.length}条字典吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const ids = multipleSelection.value.map((item) => item.dictionaryId).join(',')
                const res = await myaxios.delete('/api/Dictionary/BatchDeleteDictionary', {
                    params: { dictionaryIds: ids },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '批量删除成功')
                    fetchData()
                } else {
                    ElMessage.error(result.message || '批量删除失败')
                }
            } catch (error) {
                console.error('批量删除字典失败:', error)
                ElMessage.error('批量删除失败，请稍后重试')
            }
        })
        .catch(() => { })
}

// 导入
const handleImport = () => {
    ElMessage.warning('导入功能暂未实现')
}

// 导出文件处理函数
const downloadFile = (res: any, defaultFileName: string) => {
    // 从响应头中获取文件名
    const disposition = res.headers?.['content-disposition'] || res.headers?.['Content-Disposition']
    let fileName = defaultFileName

    if (disposition) {
        // 解析文件名，支持UTF-8编码的文件名
        const match = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(disposition)
        if (match) {
            const raw = match[1] ?? match[2]
            if (typeof raw === 'string' && raw.length > 0) {
                fileName = decodeURIComponent(raw)
            }
        }
    }

    // 创建Blob对象
    const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
}

// 导出
const handleExport = () => {
    // 检查是否有选中项，如果没有则提示用户选择
    if (!multipleSelection.value || multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要导出的字典项')
        return
    }

    // 获取选中的字典数据，前端生成Excel文件
    const selectedData = multipleSelection.value

    // 构建CSV格式的导出数据
    const headers = ['字典编号', '字典名称', '描述']
    const rows = selectedData.map((item: DictionaryItem) => [
        item.dictionaryCode || '',
        item.dictionaryName || '',
        item.description || '无',
    ])

    // CSV转义函数
    const escape = (v: any) => {
        const s = String(v).replace(/"/g, '""')
        return /[",\n]/.test(s) ? `"${s}"` : s
    }

    // 生成CSV内容
    const csv = [
        headers.map(escape).join(','),
        ...rows.map((r) => r.map(escape).join(',')),
    ].join('\n')

    // 创建Blob对象（使用UTF-8 BOM支持中文）
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = `字典_已选_${moment().format('YYYYMMDDHHmmss')}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success(`已导出选中的${selectedData.length}条字典数据`)
}

// 选择变化
const handleSelectionChange = (val: DictionaryItem[]) => {
    multipleSelection.value = val
}

// 监听分页变化
watch(
    () => [page.pageindex, page.pagesize],
    () => {
        fetchData()
    },
)

// 初始化
onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.dictionary-page {
    padding: 12px;
}

.filter-form {
    margin-top: 10px;
}

.toolbar {
    margin-bottom: 16px;
}

.pagination-card {
    margin-top: 16px;
}

.pagination-bar {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 16px;
}

.pagination-info {
    font-size: 12px;
    color: #666;
}

.pagination-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

:deep(.form-input) {
    width: 400px !important;
}

:deep(.form-input .el-input__wrapper) {
    width: 100% !important;
}

.pagination-btn {
    padding: 0 8px;
}

.pagination-jump {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    color: #666;
}

.config-toolbar {
    margin-bottom: 16px;
}

.config-pagination {
    margin-top: 16px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 16px;
}
</style>
